package com.bete.updata;

import static android.support.v4.content.ContextCompat.startActivity;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.File;

import me.jessyan.autosize.utils.LogUtils;

public class SilentUpdateService extends Service {

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    // 获取传入的新版本APK文件路径
    String apkFilePath = intent.getStringExtra(UpdateConstant.APKFILEPATH);

    if (apkFilePath != null && !apkFilePath.isEmpty()) {
// 在服务启动时执行静默安装和应用重启操作
      new Thread(new Runnable() {
        @Override
        public void run() {
          LogUtils.d(apkFilePath);
//          File apkFile = new File(apkFilePath);
          if (installApk(apkFilePath)) {
            restartApp(apkFilePath);
          } else {

          }
        }
      }).start();
    }



    return START_NOT_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  private boolean installAndRestart(String apkFilePath) {
    try {
      // 获取应用的包名
      String packageName = getPackageName();
      // 获取启动的Activity名（这里简单假设启动的Activity就是应用的主Activity）
      String mainActivityName = getPackageManager().getLaunchIntentForPackage(packageName).getComponent().getClassName();

      // 使用Root权限执行安装和启动命令
      Process process = Runtime.getRuntime().exec("su");
      DataOutputStream os = new DataOutputStream(process.getOutputStream());
      os.writeBytes("pm install -r " + apkFilePath + "\n");
      os.writeBytes("am start -n " + packageName + "/" + mainActivityName + "\n");
      os.writeBytes("exit\n");
      os.flush();
      process.waitFor();
      os.close();
      process.destroy();
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  // 静默安装APK
  private boolean installApk(String apkFilePath) {
    Process process = null;
    DataOutputStream os = null;
    try {
      LogUtils.d(apkFilePath);

//      process = Runtime.getRuntime().exec("su");
//      os = new DataOutputStream(process.getOutputStream());
//      // 执行安装命令
//      os.writeBytes("pm install -r " + apkFile.getAbsolutePath() + "\n");
//      os.writeBytes("exit\n");
//      os.flush();
//      // 等待安装完成
//      process.waitFor();

      ShellUtils.CommandResult[] result = {null};
      result[0] = ShellUtils.execCmd("pm install -r " + apkFilePath, true);
//      result[0] = ShellUtils.execCmd("pm install -r " + "/sdcard/nT01/temp/app-debug.apk", true);
      LogUtils.d(result[0].toString());
      return true;
    } catch (Exception e) {
      LogUtils.d(e.toString());
      return false;
    } finally {
      try {
        if (os != null) {
          os.close();
        }
        if (process != null) {
          process.destroy();
        }
      } catch (Exception e) {
        LogUtils.d(e.toString());
      }
    }
  }

  // 重新启动应用
  private void restartApp(String apkFilePath) {
    String packageName = getPackageNameFromApk(this,apkFilePath);
    Intent launchIntent = getPackageManager().getLaunchIntentForPackage(packageName);
    if (launchIntent != null) {
      // 清除栈并启动应用的启动 Activity
      launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
      startActivity(launchIntent);
    }
  }

  public static String getPackageNameFromApk(Context context, String apkFilePath) {
    PackageManager pm = context.getPackageManager();
    PackageInfo packageInfo = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES);
    if (packageInfo != null) {
      return packageInfo.packageName;
    }
    return null;
  }
}